/*
**    Copyright (C) 2003-2010 Institute for Systems Biology
**                            Seattle, Washington, USA.
**
**    This library is free software; you can redistribute it and/or
**    modify it under the terms of the GNU Lesser General Public
**    License as published by the Free Software Foundation; either
**    version 2.1 of the License, or (at your option) any later version.
**
**    This library is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**    Lesser General Public License for more details.
**
**    You should have received a copy of the GNU Lesser General Public
**    License along with this library; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*/

package org.systemsbiology.ml;
import org.systemsbiology.util.Clicker;
import org.systemsbiology.util.KahanSummation;
import org.systemsbiology.util.Pair;

import static java.lang.Math.*;

/**
 * Shannon Summation: compute the Shannon information entropy from a binned Clicker in discrete space
 *  This is the single-valued optimization of {@link MutualInformation}.
 * @author trobinso
 */
public class ShannonSummation<T> {

    KahanSummation wrapped = new KahanSummation();  // Uses Kahan Summation to guarantee a memory footprint of O(1) WRT
                                                    //  the input data set while minimizing roundoff error.

    public ShannonSummation(Clicker<T> given) {
        if (given == null) {
            throw new IllegalArgumentException("given Clicker<T> cannot be null");
        }

        double total = (double)given.total();
        for(Pair<T, Integer> keyvalue: given) {
            double prob = keyvalue.second / total;
            wrapped.add(prob * log(prob)/log(2));
        }
    }

    public double total() {
        return wrapped.total();    
    }
}
